package m.jclecai.com.utils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.inter.OnResultCallback;
import m.jclecai.com.utils.http.log.HttpLoggingInterceptor;

/**
 * Created by Administrator on 2017/2/9.
 */

public class OkHttpClientManager {

    protected static final int Response = 0;
    private static OkHttpClientManager okHttpClientManager;
    private OkHttpClient OkHttpClient;
    private Handler mDelivery;

    private OkHttpClientManager() {
        OkHttpClient = new OkHttpClient();
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient.interceptors().add(httpLoggingInterceptor);
        OkHttpClient.setReadTimeout(10, TimeUnit.SECONDS);
        OkHttpClient.setWriteTimeout(10, TimeUnit.SECONDS);
        OkHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);
        mDelivery = new Handler(Looper.getMainLooper());
    }

    public static synchronized OkHttpClientManager getInstance() {
        if (okHttpClientManager == null) {
            okHttpClientManager = new OkHttpClientManager();
        }
        return okHttpClientManager;
    }


    /**
     * @param url
     * @throws IOException 异步GET请求
     * @paramcallback
     */
    private void _get(final OnResultCallback callback, String url) throws IOException {
        final Request request = new Request.Builder()
                .url(formatUrl(url))
                .build();
        OkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    sendSuccessResultCallback(callback, (response.body().string()));
                }
            }

            @Override
            public void onFailure(Request arg0, IOException arg1) {
                sendFailureResultCallback(callback);
            }
        });
    }

    private String formatUrl(String url) {
        return Constant_Url.HTTP_URL + url;
    }


    /**
     * @param callback
     * @param param
     * @throws IOException 异步POST请求
     */
    private void _post(final OnResultCallback callback, Param... param) throws IOException {
        Request buildPostRequest = buildPostRequest(param);
        OkHttpClient.newCall(buildPostRequest).enqueue(new Callback() {
            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    sendSuccessResultCallback(callback, (response.body().string()));
                }
            }

            @Override
            public void onFailure(Request arg0, IOException arg1) {
                sendFailureResultCallback(callback);
            }
        });
    }


    /**
     * @param callback
     * @param json     回传数据
     */
    private void sendSuccessResultCallback(final OnResultCallback callback, final String json) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                if (callback != null) {
                    Log.i("一一一一一一一一一一一一一一一", json);
                    callback.onGetResult(json);
                }
            }
        });
    }

    /**
     * @param callback 回传失败的数据
     */
    private void sendFailureResultCallback(final OnResultCallback callback) {
        mDelivery.post(new Runnable() {

            @Override
            public void run() {
                if (callback != null) {
                    callback.onError();
                }
            }
        });

    }


    /**
     * @param param
     * @return 建造post请求所需的数据
     */

    String url;

    private Request buildPostRequest(Param[] param) {
        if (param == null) {
            param = new Param[0];
        }
        FormEncodingBuilder builder = new FormEncodingBuilder();
        for (Param p : param) {
            if (p.key.equals("url")) {
                url = p.value;
            } else {
                Log.i("一一p.key一一", p.key);
                Log.i("一一p.value一一", p.value);
                builder.add(p.key, p.value);
            }
        }
        Log.i("一一url一一", url);
        Request request = new Request.Builder().url(formatUrl(url)).post(builder.build()).build();
        return request;
    }


    /**
     * @param callback
     * @param param
     * @throws IOException 提供的公开方法
     */
    public void asynPost(OnResultCallback callback, Param... param) throws IOException {
        getInstance()._post(callback, param);
        Log.i("一一一一一一一一一一一一一一一一", "_post");
    }

    public void asynGet(OnResultCallback callback, String url) throws IOException {
        getInstance()._get(callback, url);
    }


    public static class Param {
        String value;
        String key;

        public Param() {
            // TODO Auto-generated constructor stub
        }

        public Param(String key, String value) {
            this.key = key;
            this.value = value;
        }
    }


}
